/**
 * Extract resources from HAR file
 */

const fs = require('fs');
const path = require('path');
const sHarFilePath = "../../lp-logdata/sample.har";
const sDestination = "../../dist";
const sIncludesPattern = "https://openui5.hana.ondemand.com";

/**
 * search in bing.com and copy from stackoverflow
 * source: https://stackoverflow.com/questions/15900485/correct-way-to-convert-size-in-bytes-to-kb-mb-gb-in-javascript
 */
function formatBytes(bytes, decimals = 2) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

return new Promise(function (resolve, reject) {
    // Read HAR file into JSON
    var oCtx = { oContent: {}, aPathItems: [] };
    var sContent = fs.readFileSync(path.resolve(sHarFilePath), 'utf8');
    var oContent = JSON.parse(sContent);
    oCtx.oContent = oContent;
    console.log(`pages: ${oContent.log.pages.length}`);
    console.log(`entries: ${oContent.log.entries.length}`);
    resolve(oCtx);
}).then(function (oCtx) {
    return new Promise(function (resolve, reject) {
        // Parse URL and Response payload
        var oContent = oCtx.oContent;
        var total = 0;
        for (let i = 0; i < oContent.log.entries.length; i++) {
            const oEntry = oContent.log.entries[i];
            console.log(`resp[${i}]:`);
            console.log(`- url: ${oEntry.request.url}`);
            console.log(` -size: ${formatBytes(oEntry.response.content.size)}`);
            total += oEntry.response.content.size;
            var iLastSplash = oEntry.request.url.lastIndexOf("/");
            var dir = oEntry.request.url.substring(8, iLastSplash);
            console.log(` -dir: ${dir}`);
            var file = oEntry.request.url.substr(iLastSplash + 1);
            console.log(` -file: ${file}`);
            var hasData = oEntry.response.content.text ? true : false;
            console.log(` -hasData: ${hasData}`);
            oCtx.aPathItems.push({
                dir: dir,
                file: file,
                hasData: hasData,
                text: oEntry.response.content.text
            });
        }
        console.log(`total: ${formatBytes(total)}`);
        resolve(oCtx);
    });
}).then(function (oCtx) {
    return new Promise(function (resolve, reject) {
        // Write result to files and create folders
        var aPathItems = oCtx.aPathItems;
        var step1_complete = aPathItems.length;
        var count = 0;
        aPathItems.forEach(function (oPathItem) {
            var dir = oPathItem.dir;
            var file = oPathItem.file;
            if (oPathItem.hasData === true) {
                fs.mkdir(path.resolve(sDestination, dir), { recursive: true }, (err) => {
                    process.stdout.clearLine();
                    process.stdout.cursorTo(0);
                    process.stdout.write(`progresss: [${++count}/${aPathItems.length}]`);
                    step1_complete--;
                    if (err) {
                        throw err;
                    } else {
                        fs.writeFileSync(path.resolve(sDestination, dir, file), oPathItem.text);
                        if (step1_complete === 0) {
                            resolve(oCtx);
                            console.log("");
                        }
                    }
                });
            } else {
                count++;
                step1_complete--;
            }
        });
    });
}).then(function () {
    console.log("complete");
});